package dao;

import java.util.Date;
import java.util.List;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.orm.hibernate3.HibernateTemplate;
import org.springframework.transaction.annotation.Transactional;

import beans.News;
@Transactional
public class NewsDAO {

private HibernateTemplate hibernateTemplate;

	public void setSessionFactory(SessionFactory sessionFactory){
		this.hibernateTemplate = new HibernateTemplate(sessionFactory);
	}
	
	public void saveNews(News news){
		hibernateTemplate.save(news);
	}
	public void addNews(News news){
		news.setDate(new Date());
		hibernateTemplate.save(news);
	}
	
	public List<News> GetAllNews(){
		return hibernateTemplate.loadAll(News.class);
	}

	public List<News> DisplayNews(){
		Session session = hibernateTemplate.getSessionFactory().getCurrentSession();
		session.beginTransaction();
		List<News> list;
		Query query = session.createQuery("from News order by date desc");
		list = (List<News>)query.list();
		return list;
		
	}
	
	public void UpdateNews(News news){
		hibernateTemplate.update(news);
	}
	
	public void deleteNews(News news){
		hibernateTemplate.delete(news);
	}
	
	public News findNewsById(int news_id){
		News news = new News();
		for(News x: GetAllNews()){
			if(x.getId()==news_id){
				news.setId(x.getId());
				news.setTitle(x.getTitle());
				news.setNews(x.getNews());
				news.setDate(x.getDate());
			}
		}
		return news;
	}
}
